<?php

Class PurchasePayment extends Payment {
    private static $singular_name = "E-Purchase Payment";
    private static $plural_name = "E-Purchase Payments";
    
    private static $db = array(
        'BeforeBalance' => 'Currency',
        'AfterBalance' => 'Currency'
    );
	
	private static $many_many = array(
		'PurchaseAccounts' => 'PurchaseAccount'
	);
	
	public function fieldLabels($includerelations = true) {
		$labels = parent::fieldLabels($includerelations);
		
		$labels['BeforeBalance'] = _t('PurchasePayment.BEFORE_BALANCE', 'Before Balance');
		$labels['AfterBalance'] = _t('PurchasePayment.AFTER_BALANCE', 'After Balance');
		
		return $labels;	
	}
	
	function validate() {
        $validationResult = parent::validate();

		if($this->isChanged('Status') && $this->Status == 'Success'){
			$data = array(
				'MemberID' => $this->Receipt()->MemberID,
				'Amount' => $this->Amount
			);
	        $errors = $this->getPaymentFormRequirements(RequiredFields::create(), $data)->getErrors();

			if($errors){
	        	foreach($errors as $error){
            		$validationResult->error($error['message']);
				}
            }
		}

        return $validationResult;
    }
    
    function getCMSFields(){
        $fields = parent::getCMSFields();

        $fields->makeFieldReadonly('BeforeBalance');
        $fields->makeFieldReadonly('AfterBalance');
		$fields->removeByName('PurchaseAccounts');
        
        return $fields;
    }
    
    function getPaymentFormFields($memberid){
        $fields = FieldList::create(
            $purchaseAccountBalanceField = ReadonlyField::create('PurchasePayment_ShowPurchaseAccountBalance', _t('PurchasePayment.CURRENT_BALANCE', 'Current Balance'), Account::get('PurchaseAccount', $memberid)->obj('Balance')->Nice())
        );
		
	$purchaseAccountBalanceField->setIncludeHiddenField(true);
		
	$this->extend('updatePaymentFormFields', $fields, $memberid);
		
        return $fields;
    }

    function getPaymentFormRequirements($validator, $data){
        if($data['MemberID'] == '' || !$member = DataObject::get_by_id('Member', (int)$data['MemberID'])){
            $validator->validationError(
                'Payment',
                _t('PurchasePayment.INVALID_MEMBER_ID', 'Invalid Member ID'),
                'warning'
            );
        }
        else if($data['Amount'] <= 0){
            $validator->validationError(
                'Payment',
                _t('PurchasePayment.INVALID_AMOUNT', 'Invalid Amount'),
                'warning'
            );
        }
        else if(bccomp(Account::get('PurchaseAccount', $data['MemberID'])->Balance, $data['Amount']) < 0){
            $validator->validationError(
                'PurchasePayment_ShowPurchaseAccountBalance',
                _t('PurchasePayment.INSUFFICIENT_BALANCE', 'Insufficient account balance ({balance})', 'Display insufficient purchase account balance', array('balance' => Account::get('PurchaseAccount', $data['MemberID'])->obj('Balance')->Nice())),
                'warning'
            );
        }

	$this->extend('updatePaymentFormRequirements', $validator, $data);

        return $validator;
    }

	function onBeforeWrite(){
		parent::onBeforeWrite();
		
		if($this->Amount > 0 && $this->isChanged('Status') && $this->Status == 'Success' && !$this->PurchaseAccounts()->filter('Debit:GreaterThan', 0)->count()){
            $this->setField('BeforeBalance', Account::get('PurchaseAccount', $this->Receipt()->MemberID)->Balance);
            $statement_data = array(
                'Type' => 'Purchase',
                'Debit' => $this->Amount,
                'Reference' => $this->Receipt()->Reference,
                'Description' => $this->Receipt()->TransactionType()->Description
            );
            $id = PurchaseAccount::create_statement($statement_data, $this->Receipt()->MemberID);
            $this->setField('AfterBalance', Account::get('PurchaseAccount', $this->Receipt()->MemberID)->Balance);
			$this->PurchaseAccounts()->add($id);
		}
	}
    
    function pendingPayment($data = array()){
        $this->update($data)->setField('Status', 'Pending')->write();
        return $this;
    }
    
    function failurePayment($data = array()){
        $this->update($data)->setField('Status', 'Failure')->write();
        return $this;
    }
    
    function completePayment($data = array()){
        if($this->Status == 'Incomplete' || $this->Status == 'Pending'){
            $this->update($data)->setField('Status', 'Success')->write();
        }
        
        return $this;
    }
    
    function ProcessLink(){
        $token = SecurityToken::inst();
        return $token->addToUrl(Controller::join_links('ewallet', 'process', $this->ID, $this->ClassName)) . sprintf('&locale=%s', Controller::curr()->Locale);
    }
	
    function checkBalance(){
    	return Account::get('PurchaseAccount', $this->Receipt()->MemberID)->Balance >= $this->Amount;
    }
}

?>